#include "sync_win.h"
#include "watcher.h"
#include <unistd.h>
#include <QMouseEvent>
#include <stdio.h>
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;

Sync_win::Sync_win(Watcher *p, int &p_version, bool &p_updated,
         pthread_t id, QDialog *parent) :
        QDialog(parent),updated(p_updated),version(p_version)
{
    id_proc = id;

    //隐藏窗口边框
    this->setWindowFlags(Qt::FramelessWindowHint);

    //窗体透明化
    this->setAttribute(Qt::WA_TranslucentBackground, true);

    //初始化窗体
    this->setupUi(this);

    //设置按钮透明
    quit_button->setFlat(true);

    gsyncer = p;
}

void Sync_win::mousePressEvent(QMouseEvent * event)
{
    if (event->button() == Qt::LeftButton) //点击左边鼠标
    {
         dragPosition = event->globalPos() - frameGeometry().topLeft();
         //globalPos()获取根窗口的相对路径，frameGeometry().topLeft()获取主窗口左上角的位置
         event->accept();   //鼠标事件被系统接收
    }
    if (event->button() == Qt::RightButton)
    {
         close();
    }
}

void Sync_win::mouseMoveEvent(QMouseEvent * event)
{
    if (event->buttons() == Qt::LeftButton) //当满足鼠标左键被点击时。
    {
         move(event->globalPos() - dragPosition);//移动窗口
         event->accept();
    }
}

void Sync_win::set_id(pthread_t id)
{
    id_proc = id;
}


void Sync_win::on_quit_button_clicked()
{
    gsyncer->cexit();
    //this->label->setText("正在等待同步结束，请稍等..");
    this->quit_button->hide();
    this->show();
    if(updated)
    {
        char path[PATH_LEN];
        sprintf(path,"/home/%s/gsyncer/%s/.version",cuserid(NULL),gsyncer->get_user().c_str());
        cout << path << endl;
        int fd = ::open(path,O_WRONLY|O_TRUNC);

        this->version++;
        write(fd,&version,sizeof(int));
        ::close(fd);
    }

    pthread_join(id_proc,NULL);
    sleep(1);
    this->close();
    exit(0);
}
